package models

import (
	"gorm.io/gorm"
)

// 商品表
type Goods struct {
	gorm.Model
	TypesId   int64   //分类
	Title     string  //标题
	Price     float64 //价格
	Stock     int64   //库存
	Sales     int64   //销量
	CouponsId int64   //优惠券ID
}

//商品列表展示
func (g *Goods) GetGoods(sortWord string) (listGoods []*Goods, err error) {
	query := DB.Model(&Goods{})

	if sortWord == "typesId" {
		query = query.Order("typesId desc")
	} else if sortWord == "sales" {
		query = query.Order("sales desc")
	} else if sortWord == "price" {
		query = query.Order("price desc")
	} else {
		query = query.Order("created_at desc")
	}

	err = query.Find(&listGoods).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (g *Goods) GetGoodsById(goodsId int64) error {
	return DB.Where("id=?", goodsId).Limit(1).Find(&g).Error
}

func (g *Goods) UpdateStatus(goodsStatus int64) error {
	return DB.Model(*g).Update("goods_status", goodsStatus).Error
}

type Images struct {
	gorm.Model
	GoodsId int64  `gorm:"type:int(3);comment:商品ID"`
	Url     string `gorm:"type:varchar(255);comment:图片地址"`
}

// 配送表
type Distribution struct {
	gorm.Model
}

// 优惠券类型表
type Coupons struct {
	gorm.Model
}
